import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

public class Solution {
    public static void main(String[] args) {
        int[][] arr = {{1,3,1},{1,5,1},{4,2,1}};
        System.out.println(minPathSum(arr));
    }
    //最小路径和
    public static int minPathSum(int[][] grid) {
        //共有n行，m列
        int n = grid.length;
        int m = grid[0].length;
        int[][] dp = new int[n+1][m+1];
        for(int i = 0; i <= n; i++) {
            dp[0][i] = Integer.MAX_VALUE;
        }
        for(int i = 0; i <= m; i++) {
            dp[i][0] = Integer.MAX_VALUE;
        }
        dp[0][1] = 0;
        dp[1][0] = 0;
        for(int i = 1; i <= n; i++) {
            for(int j = 1; j <= m; j++) {
                dp[i][j] = Math.min(dp[i-1][j],dp[i][j-1]) + grid[i-1][j-1];
            }
        }
        int min = Integer.MAX_VALUE;
        for(int i = 0; i < m; i++) {
            if(dp[n][i] < min) {
                min = dp[n][i];
            }
        }
        return min;
    }
    //单词拆分
    public boolean wordBreak(String s, List<String> wordDict) {
        int n = s.length();
        s = " "+s;
        StringBuilder s1 = new StringBuilder(s);
        HashSet hash = new HashSet(wordDict);
        boolean[] dp = new boolean[n+1];
        dp[0] = true;
        for(int i = 1; i < n; i++) {
            for(int j = 0; j <= i; j++) {
                if(dp[j-1] && hash.contains(s1.substring(j,i))) {
                    dp[i] = true;
                }
            }
        }
        return dp[n];
    }
}
